// packageCommunity/pages//articleDetail/index.js
import{comments} from "../../../js/modules/mall.js" 
import {wholesaleSettings,share,config} from '../../../js/modules/gloab';
import {router,pagesInfo} from '../../../js/router'; 
import BasePage from '../../../js/common/base-page' 
import {util,api,dialog,storage} from '../../../js/util'; 
import authorize from '../../../js/modules/authorize.js'
import { deepClone } from "../../../js/newUtil.js";

var app = getApp();
BasePage({ 
  pageKey: "postDetail",
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    postId:'',//帖子id
    postDetail:{},//帖子详情
    imgDomain: api.imgDomain,
    videoDomain:api.videoDomain,
    enableOss: api.enableOss,
    promoteInfo:{
      prom: {},
      name: "",
      terminal: "",
      detail: "",
      promotLadder: [],
      promoteList: []
    },
    CommentList:[],//评论列表
    replyHidden:false, //查看全部回复
    replayCon:'',//回复的内容
    currentNum:0,//多少字
    replayInfo:{
      InteractionId:'',//帖子ID
      CommentId:'',//评论ID
      ParentId:''//父级回复ID
    },
    commentName:'',//评论者姓名
    postType:'',//0--评论帖子 1---回复
    // userSid:'',
    allLookReply:[],//查看全部回复
    itemReply:{},//查看全部回复列表
    bottom:'',
    focus:false,//获取焦点 
    isIphoneX:app.globalData.isIphoneX,
    thumbWidth:800,
    thumbHeight:800,
    fitHeight:750,
    Currency:'',//货币符号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var id = '';
    // if(options.scene){
    //   id = options.scene;
    // }else{
    //   id = options.id; 
    // }
    
    this.setData({
      postId:options.id,
      // userSid:authorize.getEntity()
    })
    this.getWholesaleConfig()
  },
  /**
   * 获取配置信息
   */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      "Wholesale",
      function (model) {
        if (model.NoLoginShowInteraction == false) {
          if (!authorize.isLogin('store')) {
            authorize.redirect('store')
            return
          }
        }
        that.setData({
          NoLoginShowInteraction: model.NoLoginShowInteraction
        })
        //详情
        that.detail();
        //评论
        that.getCommontList();
        //分享详情
        that.getShareInfo();
        //累加帖子浏览量
        that.postViews();
      });
  },
  detail:function(){
    var that = this;
    var data = {Id:this.data.postId};
    comments.getPostDetail(data,function(content){
      if(content.Success){
        let storeInfo = authorize.getEntity() || {};
        var data = content.Content;
        if(data.FKFlag == storeInfo.fkFlag && data.ManagerId == storeInfo.manager.ManagerId){
          data.userDel = true;
        }else{
          data.userDel = false;
        }
        
        // if(data.ImageList[0].indexOf(',') === -1){
        //   data.ImageList = data.ImageList;
        // }else{
        //   data.ImageList = data.ImageList[0].split(',');
        // }
        try{
          //解析京东外部链接style里面的背景图
          util.linkParseImg(data.Content,(intro)=>{
            let content = util.decoratePicSrc(intro, that.data.imgDomain);
            content = content.replace(/()+/ig, "\n")
            that.setData({
              richtext_content: content
            })
          });
        }catch (e){}
        // data.Content = data.Content.replace(/<[^>]+>/g, "").replace(/()+/ig, "\n")
        if(data.Promotions){
          var config = wholesaleSettings.getConfig();
          for(var i=0;i<data.Promotions.length;i++){
            var p = data.Promotions[i];
            if (p.DiscountMode == 1 || p.DiscountMode == 4){
              p.DiscountDesc ="满减";
            }
            else if (p.DiscountMode == 2 || p.DiscountMode == 5) {
              p.DiscountDesc = "打折";
            }
            else if (p.DiscountMode == 3 || p.DiscountMode == 6) {//优惠改满赠
              p.DiscountDesc = "满赠";
            } else if (p.DiscountMode == 7) {
              p.DiscountDesc = "满降";
            }
            var info = "", isDiscountCon=false;
            if (p.DiscountMode == 1 || p.DiscountMode == 2 || p.DiscountMode == 3) {
              info = (p.PromotionType == 1 ? "单品" : "商品组合") +  "金额" + (p.DiscountCalcType == 1?"每":"")+"满"
            }
            else if (p.DiscountMode == 4 || p.DiscountMode == 5 || p.DiscountMode == 6 || p.DiscountMode == 7){
              info = (p.PromotionType == 1 ? "单品" : "商品组合") +  "数量" + (p.DiscountCalcType == 1 ? "每" : "") + "满"
              isDiscountCon=true;
            }
            var unit=""
            if (p.DiscountMode == 1 || p.DiscountMode == 2 || p.DiscountMode == 3){
              unit="元";
            }
            var action_temp="",isDiscount=false;
            if (p.DiscountMode == 1 || p.DiscountMode == 4){
              action_temp ="，立减{0}元"
            }
            else if(p.DiscountMode == 2 || p.DiscountMode == 5){
              action_temp = "，打{0}折";
              isDiscount=true;
            } else if (p.DiscountMode == 7) {
              action_temp = "，单价立降{0}元";
            }
            
            for (var j = 0; j < p.PromotLadder.length;j++){
              var pl = p.PromotLadder[j];
              pl.PromotionInfo= info + (isDiscountCon ? pl.MinimumValue : pl.MinimumValue.toFixed(2)) + unit+
                action_temp.format(isDiscount ? util.formatFloat(pl.DiscountValue * 10,config.priceDigits) : (pl.DiscountValue));
              if (pl.Gifts && pl.Gifts != "") {
                if (pl.GiftType == 1) {
                  pl.PromotionInfo += '，送本品'
                  pl += (pl.GiftsNum>0?(pl.GiftsNum + (pl.GiftsUnit||'')):'');
                } else {
                  if (pl.GiveMethod == 1) {
                    pl.PromotionInfo += `，任选${pl.GiveCount || ''}种赠品`
                  } else {
                    pl.PromotionInfo += '，送赠品'
                    pl += (pl.GiftsNum>0?(pl.GiftsNum + (pl.GiftsUnit||'')):'');
                  }
                }
              }
              if (pl.Coupons && pl.Coupons != "") {
                pl.PromotionInfo += "，送优惠劵";
              }
              if (pl.FreeFreight == 1) {
                pl.PromotionInfo += "，免邮";
              }
            }
          }
        }
        that.setData({
          postDetail:data 
        })
      }else{
        util.tips(content.Message);
        // wx.navigateBack({delta: 0})
      }
    })
  },
  /**
   * 对互动帖子、评论点赞
   */
  bindLike:function(e){ 
    if (!authorize.isLogin('store')) {
      authorize.redirect('store')
      return
    }
    var that = this;
    //0:帖子，1：评论
    var type = e.currentTarget.dataset.type;
    var id =  e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;// true - false
    var data = {Type:type,Id:id};
    var list = that.data.CommentList;
    var s = e.currentTarget.dataset.s;
    if(s==0){util.tips('审核通过后才能互动哟！');return;}
    if(!status){
      //点赞
      comments.getUserFollow(data,function(content){
        if(content.Success){
          //评论列表
          if(type == 1){
            var index = e.currentTarget.dataset.index;
            list.data[index].Hots ++;
            list.data[index].IsSupport = true;
            that.setData({
              CommentList:list
            })
            // console.log(that.data.CommentList,'-----点击',list);
          }else{
            //帖子
            // console.log(type,'-----')
            var detail = that.data.postDetail;
            detail.LikeCount ++;
            detail.IsSupport = true;
            that.setData({
              postDetail:detail
            })
          }
          // var pages = getCurrentPages(); //当前页面栈
          // if (pages.length > 1) {
          //   var beforePage = pages[pages.length - 2]; //获取上一个页面实例对象
          //   beforePage.onLoad(); //触发父页面中的方法
          // }
        }else{
          util.alert(content.Message);
        }
      })
    }else{
      //取消点赞
      comments.getUserCancel(data,function(content) {
        if(content.Success){
          if(type == 1){
            var index = e.currentTarget.dataset.index;
            list.data[index].Hots --;
            list.data[index].IsSupport = false;
            that.setData({
              CommentList:list
            })
            // console.log(that.data.CommentList,'-----点击',list);
          }else{
            //帖子
            // console.log(type,'-----')
            var detail = that.data.postDetail;
            detail.LikeCount --;
            detail.IsSupport = false;
            that.setData({
              postDetail:detail
            })
          }
          // var pages = getCurrentPages(); //当前页面栈
          // if (pages.length > 1) {
          //   var beforePage = pages[pages.length - 2]; //获取上一个页面实例对象
          //   beforePage.onLoad(); //触发父页面中的方法
          // }
        }else{
          util.alert(content.Message);
        }
      })
    }
    
  },
  /**
   * 获取分享信息
  */
  getShareInfo:function(){
    let that = this;
    let {id,postDetail} = that.data;
    let param = {
        Proprietor:app.dns.proprietor,
        ProprietorId:app.dns.proprietorId,
        PromotId:id,
        Type:'promot'
    }
    share.getinfo(param,false,function(res){
        let shareObj = {};
        shareObj.title = res.Title || postDetail.Title;
        shareObj.img = res.ImgSrc!=''?api.imgDomain+res.ImgSrc:'';
        that.setData({
            shareObj:shareObj
        })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    let {imgDomain,postDetail} = that.data;
    let path = pagesInfo.postdetail.url + `?id=${postDetail.Id}`;
    if (res.from === 'button') {
      // console.log(res.target)
    }
    return {
      title: postDetail.Title?postDetail.Title:postDetail.Content,
      imageUrl: imgDomain+postDetail.ImageList[0],
      path: path
    }
  },
  /**
   * 分享到朋友圈
   */
  onShareTimeline () {
    var that = this
    let {
      imgDomain,
      postDetail
    } = that.data;
    let query = `id=${postDetail.Id}`
    let title = postDetail.Title ? postDetail.Title : postDetail.Content
    return {
      title: title || '',
      query
    }
  },
  /**
   * 累加帖子浏览量
  */
 postViews:function(){
  var data = {InteractionId:this.data.postId}
  comments.getPostViews(data,function(content){})
 },
  /**
   * 评论列表
  */
  getCommontList:function(){
    var that = this;
    var data = {InteractionId:that.data.postId}
    comments.getPostCommentList(data,function(content){
      if(content.Success){
        let storeInfo = authorize.getEntity();
        var data = content.Content;
        for(var i=0;i<data.data.length;i++){
          if((data.data[i].FKFlag == storeInfo.fkFlag && data.data[i].ManagerId == storeInfo.manager.ManagerId) && data.data[i].IsAuthority){
            data.data[i].userDel = true;
          }else{
            data.data[i].userDel = false;
          }
        }
        that.setData({
          CommentList:data
        })
      }else{
        // 朋友圈单页模式进入此页面，不提示跳转登录
        let appLaunchData = app.globalData.appLaunchData || {}
        if (appLaunchData.scene == 1154) {
          return
        }
        // 无需登录则不提示跳转
        if (that.data.NoLoginShowInteraction == true) {
          return
        }
        util.alert(content.Message);
      }
    })
  },
  /**
  * 查看所有回复
  */
  bindAllReply:function(e){
    var that = this;
    var postid = e.currentTarget.dataset.postid;//帖子id
    var id = e.currentTarget.dataset.id;//评论Id
    var item = e.currentTarget.dataset.item;
    var data = {
      InteractionId:postid,
      CommentId:id
    };
    that.setData({
      itemReply:item,
      replyHidden:true
    })
    that.replyList(data);
  },
  replyList:function(data){
    var that = this;
    comments.getCommentList(data,function(content){ 
      if(content.Success){
        let list = content.Content.data;
        let storeInfo = authorize.getEntity();
        list.forEach(function(item){
          if((item.FKFlag == storeInfo.fkFlag && item.ManagerId == storeInfo.manager.ManagerId) && item.IsAuthority){
            item.userDel = true;
          }else{
            item.userDel = false;
          }
        })
        list = that.formatAllReply(list)
        that.setData({
          allLookReply:list
        })
      }else{
        util.alert(content.Message);
      }
    })
  },
  /**
  * 关闭回复
  */
  hideModal(){
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
  * 回复内容
  */
  bindReply:function(e){
    if (!authorize.isLogin('store')) {
      authorize.redirect('store')
      return
    }
    let {replayInfo} = this.data;
    replayInfo.InteractionId = e.currentTarget.dataset.postid;
    replayInfo.CommentId = e.currentTarget.dataset.commentid; 
    replayInfo.ParentId = e.currentTarget.dataset.parentid; 
    var name = e.currentTarget.dataset.name;
    var type = e.currentTarget.dataset.type;
    var that = this;
    dialog.showModal(that, 'showModalStatus')
    this.setData({
      replayInfo:replayInfo,
      commentName:name,
      postType:type,
      focus:true
    })
  },
  iptCon:function(e){
    let value = e.detail.value;
    this.setData({
      replayCon:value,
      currentNum:value.length
    })
  },
  /**
  * 发布
  */
  catchBox:function(){},
  btnRelease:function(e){
    var that = this;
    var replayInfo = that.data.replayInfo;
    if(!that.data.replayCon){
      util.tips('请输入内容');
      return;
    }
    // console.log(replayInfo,'----info');
    if(that.data.postType == 0){//评论帖子
      var data = {
        InteractionId:replayInfo.InteractionId,//帖子ID
        Content:that.data.replayCon//评论内容
      };
      comments.getAddComment(data,function(content){
        // console.log(content,'----content');
        if(content.Success){
          that.setData({
            replayCon:'',
            currentNum:0
          })
          dialog.hideModal(that, 'showModalStatus')
          that.getCommontList(); 
          util.tips('评论成功');
        }else{
          util.tips(content.Message);
        }
      })
    }else{//回复
      var data = {
        InteractionId:replayInfo.InteractionId,//帖子ID
        CommentId:replayInfo.CommentId, //评论ID
        ParentId:replayInfo.ParentId, //父级回复ID
        Content:that.data.replayCon
      }; 
      var datas = {
        InteractionId:replayInfo.InteractionId,
        CommentId:replayInfo.CommentId
      };
      comments.getAddReply(data,function(content){
        // console.log(content,'----content');
        if(content.Success){
          that.setData({
            replayCon:'',
            currentNum:0
          })
          util.tips('评论成功');
          dialog.hideModal(that, 'showModalStatus')
          that.replyList(datas);
          that.getCommontList(); 
        }else{
          util.alert(content.Message);
        }
      })
    }
  },
  /**
   *  删除指定评论记录
  */
  bindComment:function(e){
    var that = this;
    // var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var data = {CommentId:e.currentTarget.dataset.id};
    var list = this.data.CommentList;
    comments.getCommentRecord(data,function(content){
      if(content.Success){
        for (var i = 0; i < list.data.length; i++) {
          if (list.data[i].Id == id){
            list.data.splice(i, 1);
          }
        }
        that.setData({
          CommentList:list,
          replyHidden:false
        })
        util.tips('删除评论成功');
        // console.log(that.data.CommentList,'---删除');
      }else{
        util.alert(content.Message);
      }
    })
  },
  /**
  * 删除回复
  */
  delReply:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id
    var data = {Id:id};
    var list = this.data.allLookReply;
    comments.getReplyDel(data,function(content){
      if(content.Success){
        // console.log(content,'----del');
        for (var i = 0; i < list.length; i++) {
          if (list[i].Id == id){
            list.splice(i, 1);
          }
        }
        that.setData({
          allLookReply:list
        })
      }else{
        util.alert(content.Message);
      }
    })
  },
  formatAllReply (list = []) {
    const originList = deepClone(list)
    list = list.map((item1) => {
      originList.map((item2) => {
        if (item1.ParentId == item2.Id) {
          item1.ReplyName = item2.Name
        }
      })
      return item1
    })
    return list
  },
  bindReplyClose:function(){
    this.setData({
      replyHidden:false
    })
  },
  /**
   * 促销活动跳转
   */
  onSkipPromotion:function(e){
    var id = e.currentTarget.dataset.id;
    router.navigate({
      path:"promotionDetail",
      params:{
        id:id
      }
    })
  },
  /**
   * 优惠券跳转
   */
  bindCoupon:function(e){
    var id = e.currentTarget.dataset.id;
    router.navigate({
      path: "couponDetail",
      params: {
        couponsid:id
      }
    });
  },
  /**
  * 获取焦点--失去焦点  
  */
  focus:function(e){
    this.setData({
      bottom:e.detail.height*2-36
    })
  },
  blur:function(e){
    this.setData({
      bottom:0
    })
  },
  /**
   * 查看大图
   */
  showBigImg:function(e){
    let index = e.detail.index
    let {
      imgDomain,
      postDetail
    } = this.data
    let imgList = deepClone(postDetail.ImageList)
    let current = ''
    imgList = imgList.map((item, itemIndex) => {
      item = imgDomain + item
      if (index == itemIndex) {
        current = item
      }
      return item
    })
    wx.previewImage({
      urls: imgList,
      current
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      Currency:api.Currency || '￥'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  
})